import 'dart:math';

import 'package:fish_redux/fish_redux.dart';
import '../../../app_files.dart';
import 'action.dart';
import 'state.dart';
import 'package:flutter/rendering.dart';
import 'dart:ui';
import 'dart:typed_data';
import 'package:flutter_location/flutter_location.dart';
import 'package:flutter/material.dart' hide Action;
import 'dart:io';
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:date_format/date_format.dart';

Effect<PhotoUploadViewState> buildEffect() {
  return combineEffects(<Object, Effect<PhotoUploadViewState>>{
    Lifecycle.initState: _initState,
    PhotoUploadViewAction.onSubmit: _onSubmit,
    PhotoUploadViewAction.onTapImage: _onTapImage,
  });
}

void _initState(Action action, Context<PhotoUploadViewState> ctx) async {
  LocationData data = await LocationManager.locationManager.getLocation();
  ctx.state.data = data;
  ctx.dispatch(PhotoUploadViewActionCreator.onAction());
}

void _onSubmit(Action action, Context<PhotoUploadViewState> ctx) async {
  if (ctx.state.selectImage == null) return;
  CommonUtils.showWaitLoading(ctx.context, descText: '处理图片中');
  RenderRepaintBoundary boundary =
  ctx.state.rootWidgetKey.currentContext.findRenderObject();
  var image = await boundary.toImage(pixelRatio: window.devicePixelRatio);
  ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
  Uint8List pngBytes = byteData.buffer.asUint8List();
  File file = await CompressImageFile.compressImageData(pngBytes);
  var dir = await path_provider.getTemporaryDirectory();
  DateTime dateTime = DateTime.now();
  String timeStr = formatDate(
      dateTime, [yyyy, '', mm, '', dd, '', HH, '', nn, '', ss, '', SSS]);
  String fileName;
  if (ctx.state.type == 0)
    fileName =
    '/${ctx.state.info.userNo}_${timeStr}_${Random().nextInt(100)}.jpg';
  else if (ctx.state.type == 1)
    fileName =
    '/${ctx.state.info.pointID}_${timeStr}_${Random().nextInt(100)}.jpg';
  else
    fileName = '/${ctx.state.info.userNo}_${timeStr}_${Random().nextInt(100)}.jpg';
  var newPath = dir.absolute.path + fileName;
  File file2 = await file.copy(newPath);

  Navigator.pop(ctx.context);
  print(file2);
  Navigator.pop(ctx.context, file2);
}

void _onTapImage(Action action, Context<PhotoUploadViewState> ctx) async {
  if (ctx.state.selectImage != null) {
    int res =
    await CommonUtils.showActionSheet(ctx.context, button: ['查看', '删除']);
    if (res == 1) {
      ctx.state.selectImage = null;
      ctx.dispatch(PhotoUploadViewActionCreator.onAction());
    } else if (res == 0) {
      CommonUtils.showPhotoAlbumView(
        ctx.context,
        initialIndex: 0,
        galleryItems: <GalleryExampleItem>[
          GalleryExampleItem(
            id: '0',
            resource: ctx.state.selectImage,
          )
        ],
      );
    }
  } else {
    File imgFile =
    await CommonUtils.showImagePicker(ctx.context, cropImg: true);
    if (imgFile == null) {
      return;
    }
    ctx.state.selectImage = imgFile;
    ctx.dispatch(PhotoUploadViewActionCreator.onAction());
  }
}
